<!DOCTYPE html>
<meta charset="utf-8">
<script src="d3.v3.min.js"></script>
<script src="../../dist/alasql.js"></script>
<style>

path.link {
  fill: none;
  stroke: #666;
  stroke-width: 1.5px;
}

circle {
  fill: #ccc;
  stroke: #fff;
  stroke-width: 1.5px;
}

text {
  fill: #000;
  font: 10px sans-serif;
  pointer-events: none;
}

</style>
<body>
<script>

// get the data

alasql('SELECT * FROM CSV("force.csv",{headers:true})',[],function(data){
  var vv = alasql('SEARCH DISTINCT(UNION ALL(/[source],/[target])) FROM ?',[data]);
  alasql('CREATE GRAPH '+vv.map(function(v){return '"'+v+'"'}));

  var vvv = {};
  alasql('SEARCH VERTEX').forEach(function(v){vvv[v.name] = v.$id});

  alasql('CREATE GRAPH '+data.map(function(e){
      return '#'+vvv[e.source]+' > {[value]:'+e.value+'} > #'+vvv[e.target]+'';    
  }));

  alasql('SEARCH "Harry" PATH("Roger") EDGE SET(color="red")');
  alasql('SEARCH "Johan" PATH("Carol") EDGE SET(color="blue")');


var width = 960,
    height = 500;

var force = d3.layout.force()

    .nodes(alasql('SEARCH VERTEX D3()'))
    .links(alasql('SEARCH EDGE D3()'))

    .size([width, height])
    .linkDistance(60)
    .charge(-300)
    .on("tick", tick)
    .start();

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

// build the arrow.
svg.append("svg:defs").selectAll("marker")
    .data(["end"])      // Different link/path types can be defined here
  .enter().append("svg:marker")    // This section adds in the arrows
    .attr("id", String)
    .attr("viewBox", "0 -5 10 10")
    .attr("refX", 15)
    .attr("refY", -1.5)
    .attr("markerWidth", 6)
    .attr("markerHeight", 6)
    .attr("orient", "auto")
  .append("svg:path")
    .attr("d", "M0,-5L10,0L0,5");

// add the links and the arrows
var path = svg.append("svg:g").selectAll("path")
    .data(force.links())
  .enter().append("svg:path")
//    .attr("class", function(d) { return "link " + d.type; })
    .attr("class", "link")
    .style('stroke',function(d){
      console.log(d.color);
      return d.color;
    })

    .attr("marker-end", "url(#end)");

// define the nodes
var node = svg.selectAll(".node")
    .data(force.nodes())
  .enter().append("g")
    .attr("class", "node")
    .call(force.drag);

// add the nodes
node.append("circle")
    .attr("r", 5);

// add the text 
node.append("text")
    .attr("x", 12)
    .attr("dy", ".35em")
    .text(function(d) { return d.name; });

// add the curvy lines
function tick() {
    path.attr("d", function(d) {
        var dx = d.target.x - d.source.x,
            dy = d.target.y - d.source.y,
            dr = Math.sqrt(dx * dx + dy * dy);
        return "M" + 
            d.source.x + "," + 
            d.source.y + "A" + 
            dr + "," + dr + " 0 0,1 " + 
            d.target.x + "," + 
            d.target.y;
    });

    node
        .attr("transform", function(d) { 
  	    return "translate(" + d.x + "," + d.y + ")"; });
}


});


</script>
</body>
</html>